package cn.iocoder.yudao.module.reading.controller.app.file;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FilePresignedUrlRespVO;
import cn.iocoder.yudao.module.reading.service.file.ReadingFileService;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 用户 APP - 音频文件管理（仅用户配音功能）
 *
 * @author 李晨
 */
@Tag(name = "用户 APP - 音频文件管理")
@RestController
@RequestMapping("/reading/audio-file")
@Validated
@Slf4j
public class AudioFileController {

    @Resource
    private ReadingFileService readingFileService;
    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    // =============================================
    // 用户配音文件上传
    // =============================================

    @PostMapping("/user-recording")
    @Operation(summary = "上传用户配音文件")
    @PreAuthenticated
    public CommonResult<String> uploadUserRecording(
            @Parameter(description = "绘本ID") @RequestParam("bookId") Long bookId,
            @Parameter(description = "页面ID") @RequestParam("pageId") Long pageId,
            @Parameter(description = "配音文件") @RequestParam("recording") MultipartFile recordingFile) {

        Long userId = getLoginUserId();
        log.info("上传用户配音，用户ID: {}, 绘本ID: {}, 页面ID: {}, 文件名: {}", userId, bookId, pageId, recordingFile.getOriginalFilename());

        try {
            // 上传文件，服务层返回相对路径
            String relativePath = readingFileService.uploadUserRecording(userId, bookId, pageId, recordingFile);
            // 转换为完整URL返回给前端
            String fullUrl = staticResourceUrlUtils.toFullUrl(relativePath);
            log.info("用户配音上传成功，相对路径: {}, 完整URL: {}", relativePath, fullUrl);

            return success(fullUrl);
        } catch (Exception e) {
            log.error("上传用户配音失败", e);
            return error(500, "上传配音失败: " + e.getMessage());
        }
    }

    @GetMapping("/recording/presigned-url")
    @Operation(summary = "获取用户配音上传预签名URL")
    @PreAuthenticated
    public CommonResult<FilePresignedUrlRespVO> getUserRecordingPresignedUrl(
            @Parameter(description = "绘本ID") @RequestParam("bookId") Long bookId,
            @Parameter(description = "页面ID") @RequestParam("pageId") Long pageId,
            @Parameter(description = "文件名") @RequestParam("fileName") String fileName) {

        Long userId = getLoginUserId();

        try {
            // 生成用户配音文件路径
            String directory = cn.iocoder.yudao.module.reading.util.FilePathUtils.generateUserRecordingPath(userId, bookId, pageId, fileName);
            // 使用通用的预签名URL获取方法
            FilePresignedUrlRespVO presignedUrl = readingFileService.getAudioResourcePresignedUrl("user-recordings", userId.toString(), fileName);
            return success(presignedUrl);
        } catch (Exception e) {
            log.error("获取用户配音预签名URL失败", e);
            return error(500, "获取预签名URL失败: " + e.getMessage());
        }
    }

}
